//
//  WmcInvitationVC.swift
//  YPWatermarkCamera
//
//  Created by 赵新 on 2022/3/3.
//

import AssetsLibrary
import Kingfisher
import Photos
import UIKit
import YPBedrock

// MARK: - 扩展WmcInvitationVC + WmcNavigatorProtocol

extension WmcInvitationVC: WmcNavigatorProtocol {
    static func navigationPaths() -> [WmcNavigatorManager.Path] {
        return [.invitation]
    }

    static func willMakeNavigationVC(with parms: WmcNavigatorManager.Parms) -> UIViewController {
        return WmcInvitationVC()
    }
}

// MARK: - [WmcInvitationVC]

class WmcInvitationVC: WmcBaseVC {
    // Lifecycle

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    // Internal

    lazy var qrCodeBackgroundView: UIView = {
        let view = UIView()
        view.backgroundColor = .white
        view.layer.cornerRadius = 5
        view.layer.shadowColor = UIColor.wmc_grayH14_CCCCCC.cgColor
        view.layer.shadowOffset = .zero
        view.layer.shadowRadius = view.layer.cornerRadius
        view.layer.shadowOpacity = 0.7
        return view
    }()

    lazy var instructionsLabel: UILabel = {
        let projectName = YPApp.AppName
        let attText = "扫描二维码\n下载 \(projectName)APP".yp.makeAttributed { make in
            make.set(foregroundColor:UIColor.wmc_grayH1_1F1F29)
                .set(font: 16.yp.uiFont(weight: .medium))
            let paragraph = NSMutableParagraphStyle.YP.CreateParagraphStyle { make in
                make.set(alignment:.center)
                make.set(lineSpacing:12)
            }
            make.set(paragraphStyle:paragraph)
        }
        let label = UILabel.YP.Create(attText)
        return label
    }()

    lazy var stackView: UIStackView = {
        let stackView = UIStackView()
        stackView.axis = .horizontal
        stackView.distribution = .equalSpacing

        stackView.alignment = .fill
        stackView.spacing = 5
        stackView.yp.arrangedSubviews = [wechatBtn, saveImageBtn]
        return stackView
    }()

    lazy var wechatBtn: WmcTopImgBottomTextBtn = {
        let btn = WmcTopImgBottomTextBtn(title: "分享到微信", image: "wechat_icon_color".wmc_image)
        btn.font = 14.wmc_font
        btn.imgSize = 32.wmc_autoHor
        btn.textColor = .wmc_grayH2_323233
        btn.imgTextSpacing = 8
        return btn
    }()

    lazy var saveImageBtn: WmcTopImgBottomTextBtn = {
        let btn = WmcTopImgBottomTextBtn(title: "保存到相册", image: "best_save_album".wmc_image)
        btn.font = 14.wmc_font
        btn.imgSize = 32.wmc_autoHor
        btn.textColor = .wmc_grayH2_323233
        btn.imgTextSpacing = 8
        return btn
    }()

    lazy var lineView: UIView = {
        let view = UIView()
        view.backgroundColor = .wmc_lineColor
        return view
    }()

    override func makeUI() {
        makeNavView(showShadow: false)
        title = "推荐给好友"

        addSubview(qrCodeBackgroundView)
        qrCodeBackgroundView.snp.makeConstraints { make in
            make.top.equalTo(navView.snp.bottom).offset(35)
            make.size.equalTo(250.wmc_autoHor)
            make.centerX.equalToSuperview()
        }

        qrCodeBackgroundView.addSubview(qrCodeImageView)
        qrCodeImageView.snp.makeConstraints { make in
            make.left.top.equalTo(10)
            make.right.bottom.equalTo(-10)
        }

        qrCodeImageView.addSubview(iconImageView)
        iconImageView.snp.makeConstraints { make in
            make.center.equalToSuperview()
            make.width.height.equalTo(60)
        }

        addSubview(instructionsLabel)
        instructionsLabel.snp.makeConstraints { make in
            make.top.equalTo(qrCodeBackgroundView.snp.bottom).offset(20)
            make.left.right.equalToSuperview()
        }

        addSubview(stackView)
        stackView.snp.makeConstraints { make in
            make.top.equalTo(instructionsLabel.snp.bottom).offset(80)
            make.left.equalTo(80)
            make.right.equalTo(-80)
            make.height.equalTo(60)
        }

        addSubview(lineView)
        lineView.snp.makeConstraints { make in
            make.centerX.equalTo(stackView)
            make.width.equalTo(1)
            make.top.equalTo(stackView).offset(15)
            make.bottom.equalTo(stackView).offset(-15)
        }
    }

    override func bindViewModel() {
        viewModel.fetchRecommendInfo().subscribe(onNext: { [weak self] model in
            guard let weakSelf = self else {
                return
            }
            weakSelf.qrCodeImageView.image = model.url.yp.qrCodeImage
            weakSelf.iconImageView.kf.setImage(with: URL(string: model.img), placeholder: UIImage.YP.AppIcon)
        }, onError: { error in

        }).disposed(by: rx.disposeBag)

        wechatBtn.rx.controlEvent(.touchUpInside).subscribe { [weak self] _ in
            guard let weakSelf = self,
                  let recommendModel = weakSelf.viewModel.recommendModel else { return }
            let icon = UIImage.YP.AppIcon

            let shareAlertView = WmcShareAlertView()
            let sharedConfig: WmcShareAlertView.ShareType.Config =
                .init(title: recommendModel.title, description: recommendModel.content, thumbImage: icon)
            shareAlertView.shareType = .link(recommendModel.url, config: sharedConfig)

            let height = Wmc_safeAreaBottom + 214
            let presentVC = WmcPresentVC(config: .init(style: .sheet(), contentView: shareAlertView, contentLayoutBlock: { make in
                make.left.right.bottom.equalToSuperview()
                make.height.equalTo(height)
            }))
            presentVC.show()

        }.disposed(by: rx.disposeBag)

        saveImageBtn.rx.controlEvent(.touchUpInside).subscribe { [weak self] _ in
            guard let weakSelf = self, let img = weakSelf.qrCodeBackgroundView.yp.screenshot() else { return }
            weakSelf.saveImageToPhotoLibrary(image: img)
        }.disposed(by: rx.disposeBag)
    }

    // Private

    private lazy var viewModel: WmcInvitaionVM = {
        let vm = WmcInvitaionVM()
        return vm
    }()

    private lazy var qrCodeImageView: UIImageView = {
        let imageView = UIImageView(image: "feedback_qr_icon".wmc_image)
        imageView.backgroundColor = .lightGray
        return imageView
    }()

    private lazy var iconImageView: UIImageView = {
        let imageView = UIImageView()
        imageView.image = UIImage.YP.AppIcon
        return imageView
    }()

    private func saveImageToPhotoLibrary(image: UIImage) {
        let photoAlbumStatus = WmcAuthorizedManager.photoAlbum()
        if photoAlbumStatus.info.isAvailable {
            UIImageWriteToSavedPhotosAlbum(image, self, #selector(self.saveImage(_:didFinishSaving:contextInfo:)), nil)
        } else {
            WmcAuthorizedManager.handleAlbumAuthorizationNotAvailable()
        }
    }

    @objc
    private func saveImage(_ image: UIImage, didFinishSaving error: Error?, contextInfo: AnyObject) {
        if error != nil {
            WmcHudManager.toast("保存失败")
        } else {
            WmcHudManager.toast("保存成功")
        }
    }

    private func saveImage(image: UIImage) {
        PHPhotoLibrary.shared().performChanges({
            PHAssetChangeRequest.creationRequestForAsset(from: image)
        }, completionHandler: { (success, error) in
            DispatchQueue.main.async {
                if success {
                    WmcHudManager.toast("保存成功")
                } else {
                    WmcHudManager.toast("保存失败")
                }
            }
        })
    }
}
